<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <!-- 操作按钮 -->
      <div class="base-content-operate">
        <el-button
          v-if="submitStatus === '1'"
          :disabled="selectDownLoadId.length === 0"
          type="primary"
          @click="batchDownLoad"
          >批量下载</el-button
        >
      </div>
      <!-- 列表内容 -->

      <el-table
        class="filter unsetborder"
        :data="list"
        :class="{ 'show-filter': showFilterRow }"
        element-loading-text="Loading"
        fit
        height="250"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="submitStatus === '1'" type="selection">
          <el-table-column
            type="selection"
            :selectable="filterSelection"
          ></el-table-column>
        </el-table-column>

        <el-table-column align="center" width="50">
          <template #header>
            <div class="filter-icon" title="筛选">
              <SvgIcon
                class-name="filter"
                icon-class="filter"
                @click="filterIconClick"
              />
            </div>
          </template>
          <el-table-column width="50"></el-table-column>
        </el-table-column>

        <el-table-column label="实验编号">
          <el-table-column prop="experimentNumber">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.experimentNumber"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="模板名称">
          <el-table-column prop="templateName">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.templateName"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="检测项目">
          <el-table-column prop="detectionItemName">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.detectionItemName"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="样品编号">
          <el-table-column prop="sampleNumber">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.sampleNumber"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="检测人">
          <el-table-column prop="testerName">
            <template #header>
              <el-select
                ref="selectDom"
                v-model="queryForm.creatorId"
                :multiple="false"
                placeholder="请选择检测人"
                filterable
                remote
                reserve-keyword
                :remote-method="remoteUser"
                :loading="searchUserLoading"
                value-key="id"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="开展时间">
          <el-table-column prop="detectionTime">
            <template #header>
              <el-date-picker
                v-model="queryForm.creatorTime"
                type="datetimerange"
                align="left"
                :picker-options="expireTimeOption"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="状态">
          <el-table-column>
            <template #header>
              <el-select v-model="queryForm.status" placeholder="请选择">
                <el-option
                  v-for="item in LENStatusColorMap"
                  :key="item.status"
                  :label="item.label"
                  :value="item.status"
                ></el-option>
              </el-select>
            </template>
            <template v-slot="scope">
              <div :style="{ color: getStatusColor(scope.row.status) }">
                {{ scope.row.statusDescription }}
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="来源">
          <el-table-column>
            <template #header>
              <el-select v-model="queryForm.source" placeholder="请选择">
                <el-option label="App" value="0"></el-option>
                <el-option label="PC端" value="1"></el-option>
                <el-option label="检测任务" value="2"></el-option>
              </el-select>
            </template>
            <template v-slot="scope">
              <div>
                {{
                  scope.row.source === 1
                    ? "PC端"
                    : scope.row.source === 0
                    ? "APP"
                    : "检测任务"
                }}
              </div>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="任务编号">
          <el-table-column prop="entrustTaskNum">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.entrustTaskNum"
                @keyup.enter.native="onQuery"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作">
          <el-table-column>
            <template #header>
              <div v-if="showFilterRow" class="search-operate">
                <el-link type="primary" @click="onQuery">搜索</el-link>
                <el-link @click="cancelForm">清空</el-link>
              </div>
            </template>
            <template v-slot="scope">
              <div class="base-table-operation">
                <el-link
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.row, true)"
                  >查看</el-link
                >

                <el-link
                  v-if="submitStatus === '1'"
                  v-rights="'Invalid'"
                  size="mini"
                  type="danger"
                  :disabled="scope.row.status === 70"
                  @click="discard(scope.row)"
                  >作废</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>

      <BasePagination
        v-if="showPagination"
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>
    <!-- 新建页面 -->
    <ExperimentTemplateRecordAdd
      ref="ExperimentTemplateRecordAdd"
      :dialog-form-visible.sync="dialogFormVisibleAdd"
      @callback="getList"
    />
    <!-- 编辑页面 -->
    <ExperimentTemplateRecordEdit
      v-if="dialogFormVisibleEdit"
      ref="ExperimentTemplateRecordEdit"
      v-model="recordData"
      :page-view-mode="pageViewMode"
      :dialog-form-visible.sync="dialogFormVisibleEdit"
      :readonly="readonly"
      :auto-down-zip="autoDownZip"
      @callback="getList"
    />
    <!-- 审批页面 -->
    <ExperimentTemplateRecordDialog
      ref="ExperimentTemplateRecordDialog"
      :data="data"
      :type="type"
      :dialog-form-visible.sync="dialogFormVisible"
    />
  </div>
</template>
<script>
import {
  getStandBookList,
  getSingleList,
  deleteRecord,
} from "../../../api/Eln/ExperimentTemplateRecord.js";
import { getList as getItemList } from "../../../api/Eln/ExperimentDetectionItem.js";
import ExperimentTemplateRecordAdd from "./ExperimentTemplateRecordAdd.vue";
import ExperimentTemplateRecordEdit from "./ExperimentTemplateRecordEdit.vue";
import ExperimentTemplateRecordDialog from "./ExperimentTemplateRecordDialog.vue";
import { deepClone } from "../../../utils";
import { deleteConfirm } from "../../../utils/Helper";
import { getUserListNoPage } from "../../../api/Permission/user.js";
export default {
  name: "ExperimentStandBookList",
  components: {
    ExperimentTemplateRecordAdd,
    ExperimentTemplateRecordEdit,
    ExperimentTemplateRecordDialog,
  },
  data() {
    return {
      loading: true,
      showLoading: false,
      list: [],
      showFilterRow: false,
      selectDownLoadId: [],
      selectDownLoadData: [],
      showPagination: true,
      recordData: null,
      pageViewMode: "runtime",
      readonly: false,
      searchUserLoading: false,
      autoDownZip: false,
      userList: [],
      searchExperimentItem: false,
      exprimentItemList: [],
      data: {},
      type: "",
      expireTimeOption: {
        selectableRange: "00:00:00 - 23:59:59",
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      LENStatusColorMap: [
        {
          label: "待审核",
          status: 10,
          color: "#FB7601",
        },
        {
          label: "审核中",
          status: 20,
          color: "#3E9CF3",
        },
        {
          label: "审核通过",
          status: 30,
          color: "#3CBB88",
        },
        {
          label: "审核不通过",
          status: 40,
          color: "#FF0700",
        },
        {
          label: "已完成",
          status: 50,
          color: "#ACB0B8",
        },
        {
          label: "审批撤回",
          status: 60,
          color: "#FF0700",
        },
        {
          label: "作废",
          status: 70,
          color: "#ACB0B8",
        },
      ],
      dialogFormVisible: false,
      dialogFormVisibleAdd: false,
      dialogFormVisibleEdit: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      queryForm: {
        templateCode: undefined,
        templateName: undefined,
        sampleCategoryName: undefined,
        articleNumber: undefined,
        status: undefined,
        source: undefined,
        creatorId: undefined,
        creatorTime: [],
        sampleNumber: undefined,
        experimentNumber: undefined,
      },
      submitStatus: "1",
    };
  },
  computed: {
    getStatusColor() {
      return (status) =>
        this.LENStatusColorMap.find((x) => x.status === status)?.color || "";
    },
  },
  created() {
    this.getList();
    this.remoteUser();
  },
  methods: {
    // 获取列表数据  arguments.length > 1: 编辑弹窗更新数据触发
    getList(queryForm = {}) {
      arguments.length > 1 && (queryForm = {});
      this.loading = true;
      getStandBookList({
        ...this.pagination,
        ...queryForm,
        submitStatus: Number(this.submitStatus),
      })
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    assembleQueryFormData() {
      const cloneForm = deepClone(this.queryForm);
      const creatorTime = cloneForm.creatorTime || [];
      cloneForm.startTime = creatorTime[0];
      cloneForm.endTime = creatorTime[1];
      delete cloneForm.creatorTime;
      return cloneForm;
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList(this.assembleQueryFormData());
    },
    cancelForm() {
      this.queryForm = this.$options.data().queryForm;
    },
    // 新增
    onNew() {
      this.dialogFormVisibleAdd = true;
    },
    // 编辑/查看
    handleEdit(rowData, readonly) {
      getSingleList({ Id: rowData.id }).then((res) => {
        this.autoDownZip = false;
        this.pageViewMode = "runtime";
        this.recordData = deepClone(res.data);
        this.readonly = !!readonly;
        this.dialogFormVisibleEdit = true;
      });
    },
    // 删除
    handleDelete(val) {
      const deleteFn = () => {
        deleteRecord({ id: val.id }).then((res) => {
          res.code === 200 && this.getList();
        });
      };
      deleteConfirm(deleteFn);
    },
    changeTab() {
      this.showPagination = false;
      this.showFilterRow = false;

      this.$nextTick(() => {
        this.showPagination = true;
      });
      this.getList();
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList(this.assembleQueryFormData());
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList(this.assembleQueryFormData());
    },
    // 审核
    examine(val) {
      this.data = val;
      this.type = "verify";
      this.dialogFormVisible = true;
    },
    // 作废
    discard(val) {
      this.data = val;
      this.type = "discard";
      this.dialogFormVisible = true;
    },
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name }).then((res) => {
          resolve(res);
        });
      });
    },
    // 搜索人员
    async remoteUser(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.data) {
        this.userList = filter.data || [];
      }
      this.searchUserLoading = false;
    },
    getExperimentItem(name = "") {
      return new Promise((resolve) => {
        getItemList({ name: name, pageIndex: 1, pageSize: 99 }).then((res) => {
          resolve(res);
        });
      });
    },
    // 搜素检测项目
    async remoteItem(query) {
      this.searchExperimentItem = true;
      const filter = await this.getExperimentItem(query);
      if (filter && filter.data) {
        this.exprimentItemList = filter.data || [];
      }
      this.searchExperimentItem = false;
    },
    filterIconClick() {
      this.showFilterRow = !this.showFilterRow;
      !this.showFilterRow && this.cancelForm();
    },
    handleSelectionChange(val) {
      this.selectDownLoadId = val.filter((x) => x.status === 50);
    },
    // 允许选择的复选框
    filterSelection(row) {
      return row.status === 50;
    },
    // 批量下载实验记录单
    batchDownLoad() {
      const promiseList = [];
      this.selectDownLoadId.forEach((x) => {
        promiseList.push(getSingleList({ Id: x.id }));
      });
      Promise.all(promiseList).then((res) => {
        this.showLoading = true;
        this.autoDownZip = true;
        this.pageViewMode = "print";
        this.recordData = res.map((v) => v.data);
        this.dialogFormVisibleEdit = true;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-checkbox.is-disabled.is-checked {
  .el-checkbox__inner::after {
    display: none;
  }
}
</style>
